package com.xy.p2p.service.impl;


import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xy.common.page.Pagination;
import com.xy.common.util.DictUtils;
import com.xy.common.util.EmailTools;
import com.xy.common.util.ErFen;
import com.xy.core.service.impl.BaseServiceImpl;
import com.xy.core.util.BeanUtil;
import com.xy.core.util.DateUtil;
import com.xy.mail.MailSenderInfo;
import com.xy.mail.SimpleMailSender;
import com.xy.p2p.dao.TfinanceauditDao;
import com.xy.p2p.dao.TfinanceinfoDao;
import com.xy.p2p.dao.TmemberassetaccountDao;
import com.xy.p2p.dao.TmemberassetaccountdetailsDao;
import com.xy.p2p.dao.TmembercreditDao;
import com.xy.p2p.dao.TmemberratesDao;
import com.xy.p2p.dao.TtenderrecordDao;
import com.xy.p2p.model.FinanceHelper;
import com.xy.p2p.model.Tfinanceaudit;
import com.xy.p2p.model.Tfinanceinfo;
import com.xy.p2p.model.Tmember;
import com.xy.p2p.model.Tmemberassetaccount;
import com.xy.p2p.model.Tmemberassetaccountdetails;
import com.xy.p2p.model.Tmemberbankcard;
import com.xy.p2p.model.Tmembercredit;
import com.xy.p2p.model.Tmemberrates;
import com.xy.p2p.model.Ttenderrecord;
import com.xy.p2p.model.Tuser;
import com.xy.p2p.service.TfinanceinfoService;
import com.xy.p2p.service.TmemberbankcardService;
import com.xy.p2p.service.TmembercreditService;
import com.xy.p2p.service.TmemberratesService;
import com.xy.p2p.service.TtenderrecordService;

@Service
@Transactional
public class TfinanceinfoServiceImpl extends BaseServiceImpl<Tfinanceinfo> implements
 TfinanceinfoService {
	private TfinanceinfoDao tfinanceinfoDao;

	// 标的审批不通过 审核不通过
	private final int TFINANCEINFO_STATUS_FAIL = -1;
	// 标的审批通过 投标中
	private final int TFINANCEINFO_STATUS_SUCCESS = 2;
	// 通过放款 还款中
	private final int TFINANCEINFO_STATUS_LOAN_SUCCESS = 7;
	// 不通过放款 融资失败
	private final int TFINANCEINFO_STATUS_LOAN_FAIL = 10;
	// 余额贷
	private final int TFINANCEINFO_TARGETTYPE_YED = 8;

	//本金
	private final String benjin = "principalMonth";
	//利息
	private final String lixi = "interestMonth"; 
	//每月付息到期还本 - 本息
	private final String benxi = "payPerMonth";

	// 8：还清
	private final int TFINANCEINFO_STATUS_CLEAR = 8;
	@Autowired
	private TtenderrecordDao ttenderrecordDao;
	@Autowired
	private TfinanceauditDao tfinanceauditDao;
	@Autowired
	private TmembercreditDao tmembercreditDao;
	@Autowired
	private TmemberratesDao tmemberratesDao;
	@Autowired
	private TmemberassetaccountDao tmemberassetaccountDao;
	@Autowired
	private TmemberassetaccountdetailsDao tmemberassetaccountdetailsDao;
	@Autowired
	private TmemberratesService tmemberratesService;
	@Autowired
	private TmemberbankcardService tmemberbankcardService;
	@Autowired
	private TmembercreditService tmembercreditService;
	@Autowired
	private TtenderrecordService ttenderrecordService;

	public TfinanceinfoServiceImpl(TfinanceinfoDao paramAppRoleDao) {
		super(paramAppRoleDao);
		this.tfinanceinfoDao = paramAppRoleDao;
	}

	@Override
	public boolean checkExist(String paraName, String paraValue) {
		return tfinanceinfoDao.checkExist("Tfinanceinfo", paraName, paraValue);
	}

	@Override
	public List<Tfinanceinfo> getTfinanceinfo(Map<String, Object> map) {
		return tfinanceinfoDao.getTfinanceinfo(map);
	}

	@Override
	public Pagination getTfinanceinfoByPage(Map<String, Object> map, int pageNo, int pageSize) {
		// TODO Auto-generated method stub
		return tfinanceinfoDao.getTfinanceinfoByPage(map, pageNo, pageSize);
	}

	@Override
	public Tfinanceinfo save(Tfinanceinfo tfinanceinfo) {
		if (tfinanceinfo.getFiid() == null) {
			// 新增
			tfinanceinfo.setApplicationdate(new Date());
			return super.save(tfinanceinfo);
		} else {
			// 更新
			Tfinanceinfo tfinanceinfo1 = tfinanceinfoDao.get(tfinanceinfo.getFiid());
			try {
				BeanUtil.copyNotNullProperties(tfinanceinfo1, tfinanceinfo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return super.save(tfinanceinfo1);
		}
	}

	@Override
	public boolean checkNull(Tmember tmember) {
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getTruename()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getSex()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getIdcard()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getBirthday()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getPhone()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getEmail()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getEdudegree()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getMarriage()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getAddr()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getWorktype()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getCorpindustry()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getCorpsize()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getPosition()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getEcname()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getEcphone()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getQq()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getWorkaddr()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getWorkexperience()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getCbcredit()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getFixedassets()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getCurrentassets()))
			return true;
		if (TfinanceinfoServiceImpl.checkProEmpty(tmember.getTitles()))
			return true;
		// if(TfinanceinfoServiceImpl.checkProEmpty(tmember.getHeadurl()))
		// return true;
		return false;
	}

	// just for ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
	private static boolean checkProEmpty(Object object) {
		if (null == object || "" == object.toString())
			return true;
		return false;
	}

	// 查询可投标的标的
	@Override
	public List<Tfinanceinfo> getEnableFinance() {
		List<Tfinanceinfo> enableList = tfinanceinfoDao.getEnableFinanceInfo();
		enableList.addAll(tfinanceinfoDao.getFullFinanceInfo());
		for (Tfinanceinfo t : enableList) {
			putTenderMoneyIntoEntity(t);
			// double sum =0;
			// Set<Ttenderrecord> set = t.getTtenderrecords();
			// for(Ttenderrecord tender : set){
			// sum += tender.getTdmoney();
			// }
			// if(sum<t.getFinanceamount())
			// result.add(t);
			// 为属性已投标金额赋值
			// t.setTotaltendermoney(sum);
		}
		// 将已满标的记录填充到后面
		// return result;
		// 暂时不用判断是否满标
		return enableList;
	}
	
	@Override
	public Tfinanceinfo putTenderMoneyIntoEntity(Tfinanceinfo tfinanceinfo) {
		double sum = 0;
		Set<Ttenderrecord> set = tfinanceinfo.getTtenderrecords();
		for (Ttenderrecord tender : set) {
			sum += tender.getTdmoney();
		}
		// 为属性已投标金额赋值
		tfinanceinfo.setTotaltendermoney(sum);
		return tfinanceinfo;
	}

	// 后台审核标的
	public Tfinanceinfo audit(long fiid, String opr, String opinion, Tuser tuser) {
		if (!opr.equals("0") && !opr.equals("1")) {
			return null;
		}
		Tfinanceinfo tfinanceinfo = tfinanceinfoDao.get(fiid);
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("Tfinanceinfo", tfinanceinfo);
		Tfinanceaudit tfinanceaudit;
		if (tfinanceauditDao.getTfinanceaudit(queryMap).size() <= 0) {
			tfinanceaudit = new Tfinanceaudit();
			tfinanceaudit.setTfinanceinfo(tfinanceinfo);
			tfinanceaudit.setTuserByReviewed1(tuser);
			tfinanceaudit.setAuditopinion1(opinion);
			tfinanceaudit.setRevieweddate1(new Date());
		} else {
			tfinanceaudit = tfinanceauditDao.getTfinanceaudit(queryMap).get(0);
			tfinanceaudit.setTuserByReviewed1(tuser);
			tfinanceaudit.setAuditopinion1(opinion);
			tfinanceaudit.setRevieweddate1(new Date());
		}
		if (opr.equals("0")) {
			// 审批不通过
			tfinanceinfo.setStatus(TFINANCEINFO_STATUS_FAIL);
			tfinanceaudit.setAuditresults1(TFINANCEINFO_STATUS_FAIL);
			tfinanceauditDao.save(tfinanceaudit);
			return tfinanceinfoDao.save(tfinanceinfo);
		} else if (opr.equals("1")) {
			// 审批通过
			tfinanceinfo.setStatus(TFINANCEINFO_STATUS_SUCCESS);
			tfinanceaudit.setAuditresults1(TFINANCEINFO_STATUS_SUCCESS);
			tfinanceauditDao.save(tfinanceaudit);
			return tfinanceinfoDao.save(tfinanceinfo);
		} else
			return null;
	}

	// 放款
	@Override
	public Tfinanceinfo loan(Tfinanceinfo tfinanceinfo, String opr, Tuser tuser) {
		if (!opr.equals("0") && !opr.equals("1")) {
			return null;
		}
		if (tfinanceinfoDao.get(tfinanceinfo.getFiid()).getStatus() != 4)
			return null;
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("Tfinanceinfo", tfinanceinfo);
		Map<String, Object> tmemberMap = new HashMap<String, Object>();
		Tmember tmember = tfinanceinfo.getTmember();
		tmemberMap.put("Tmember", tmember);
		if (opr.equals("0")) {
			// 不通过放款
			clearTenderAccount(tfinanceinfo);
			tfinanceinfo.setStatus(TFINANCEINFO_STATUS_LOAN_FAIL);
			return tfinanceinfoDao.save(tfinanceinfo);
		} else if (opr.equals("1")) {
			// 通过放款
			// 修改标的审核表
			Tfinanceaudit tfinanceaudit = tfinanceauditDao.getTfinanceaudit(queryMap).get(0);
			tfinanceaudit.setTuserByLenders(tuser);
			tfinanceaudit.setLoandate(new Date());
			tfinanceauditDao.save(tfinanceaudit);
			double rate = this.getRateFormTmember(tmember);
			double money = tfinanceinfo.getFinanceamount() * (1 - rate);
			// 修改账户信息
			Tmemberassetaccount tmemberassetaccount = tmemberassetaccountDao.getTmemberassetaccount(tmemberMap).get(0);
			tmemberassetaccount.setBalance(tmemberassetaccount.getBalance() + money);
			tmemberassetaccountDao.save(tmemberassetaccount);
			// 新增明细
			Tmemberassetaccountdetails td1 = new Tmemberassetaccountdetails(tmember, money + rate * tfinanceinfo.getFinanceamount(), Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_IN,
					Tmemberassetaccountdetails.TRANTYPE_BORROWIN, new Date(), "平台", null);
			tmemberassetaccountdetailsDao.save(td1);
			Tmemberassetaccountdetails td2 = new Tmemberassetaccountdetails(tmember, rate * tfinanceinfo.getFinanceamount(), Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_OUT,
					Tmemberassetaccountdetails.TRANTYPE_SERVICEFEE, new Date(), "平台", null);
			tmemberassetaccountdetailsDao.save(td2);
			// 投资用户金额解冻
			unfreezeTenderAccount(tfinanceinfo);
			// 修改标的状态
			tfinanceinfo.setStatus(TFINANCEINFO_STATUS_LOAN_SUCCESS);
			tfinanceinfo.setItfdate(new Date());
			tfinanceinfo.setNrdate(DateUtil.addMonth(new Date(), 1));
			tfinanceinfo.setPlsf(rate);
			queryMap.clear();
			queryMap.put("feedcode", Tmemberrates.RATE_MAMAGEMENT);
			Tmemberrates tmemberrates = tmemberratesDao.getTmemberrates(queryMap).get(0);
			tfinanceinfo.setMfrl(tmemberrates.getRates());
			// 判断标的限期是否在一个月之内, 如果在一个月之内的需要安排一次性付款
			if (tfinanceinfo.getFinanceallotedtime() / 30 < 1) {
				tfinanceinfo.setSubpri(tfinanceinfo.getFinanceamount());
				tfinanceinfo.setAlino(ErFen.disposable(tfinanceinfo.getFinanceamount(), tfinanceinfo.getFinancepa(), tfinanceinfo.getFinanceallotedtime()));
				tfinanceinfo.setMftba(tfinanceinfo.getFinanceamount() * tmemberrates.getRates());
				tfinanceinfo.setNrdate(DateUtil.addDate(new Date(), tfinanceinfo.getFinanceallotedtime()));
			} else {
					//等额本息
				if (tfinanceinfo.getRepaymentmod() == 1 || tfinanceinfo.getRepaymentmod() == 2) {
					List<Map<String, Double>> payList = ErFen.principal(tfinanceinfo.getFinanceamount(), tfinanceinfo.getFinancepa() / 12, tfinanceinfo.getFinanceallotedtime() / 30);
					Map<String, Double> payMap = payList.get(0);
					tfinanceinfo.setSubpri(payMap.get("principalMonth"));
					tfinanceinfo.setAlino(payMap.get("interestMonth"));
					tfinanceinfo.setMftba(tfinanceinfo.getFinanceamount() * tmemberrates.getRates());
					tfinanceinfo.setNrdate(DateUtil.addMonth(new Date(), 1));
				} else if (tfinanceinfo.getRepaymentmod() == 3) {
					//每月付息,到期还本
					System.out.println("每月付息,到期还本");
					tfinanceinfo.setSubpri(0.0);
					tfinanceinfo.setAlino(ErFen.culMonthlyInterest(tfinanceinfo.getFinanceamount(), tfinanceinfo.getFinancepa()));
					tfinanceinfo.setMftba(tfinanceinfo.getFinanceamount() * tmemberrates.getRates());
					tfinanceinfo.setNrdate(DateUtil.addMonth(new Date(), 1));
				}
				// 发送放款邮件
				sendFullMail(tfinanceinfo.getFiid());
				// 所有投资者
				Set<Ttenderrecord> tenderSet = tfinanceinfo.getTtenderrecords();
				for (Ttenderrecord t : tenderSet) {
					ttenderrecordService.sendInvestorMail(t.getTrid());
				}
				return tfinanceinfoDao.save(tfinanceinfo);
			}
		} 
			return null;
	}

	/**
	 * 获取费率
	 * 
	 * @param tmember对象
	 * @return 费率
	 */
	private double getRateFormTmember(Tmember tmember) {
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("Tmember", tmember);
		Tmembercredit tmembercredit = tmembercreditDao.getTmembercredit(queryMap).get(0);
		queryMap.clear();
		queryMap.put("feedcode", Tmemberrates.PRE_RATE_SERVICE + tmembercredit.getCreditrating());
		Tmemberrates tmemberrates = tmemberratesDao.getTmemberrates(queryMap).get(0);
		return tmemberrates.getRates();
	}

	/**
	 * 解冻投标用户金额(投标成功)
	 * 
	 * @param tfinanceinfo
	 */
	private void unfreezeTenderAccount(Tfinanceinfo tfinanceinfo) {
		Set<Ttenderrecord> ttenderSet = tfinanceinfo.getTtenderrecords();
		Map<String, Object> map = new HashMap<String, Object>();
		for (Ttenderrecord t : ttenderSet) {
			double money = t.getTdmoney();
			Tmember tmember = t.getTmember();
			map.put("Tmember", tmember);
			Tmemberassetaccount tmemberassetaccount = tmemberassetaccountDao.getTmemberassetaccount(map).get(0);
			tmemberassetaccount.setAmountfrozen(tmemberassetaccount.getAmountfrozen() - money);
			tmemberassetaccount.setAfreason(null);
			Tmemberassetaccountdetails tmemberassetaccountdetails = new Tmemberassetaccountdetails(tmember, money, Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_OUT,
					Tmemberassetaccountdetails.TRANTYPE_BORROWOUT, new Date(), tfinanceinfo.getFiid().toString(), null);
			tmemberassetaccountdetailsDao.save(tmemberassetaccountdetails);
			tmemberassetaccountDao.save(tmemberassetaccount);
			t.setMibmoney(t.getTdmoney());
			ttenderrecordDao.save(t);
		}
	}

	/**
	 * 解冻投标用户金额(投标失败)
	 * 
	 * @param tfinanceinfo
	 */
	private void clearTenderAccount(Tfinanceinfo tfinanceinfo) {
		Set<Ttenderrecord> ttenderSet = tfinanceinfo.getTtenderrecords();
		Map<String, Object> map = new HashMap<String, Object>();
		for (Ttenderrecord t : ttenderSet) {
			double money = t.getTdmoney();
			Tmember tmember = t.getTmember();
			map.put("Tmember", tmember);
			Tmemberassetaccount tmemberassetaccount = tmemberassetaccountDao.getTmemberassetaccount(map).get(0);
			tmemberassetaccount.setAmountfrozen(tmemberassetaccount.getAmountfrozen() - money);
			tmemberassetaccount.setBalance(tmemberassetaccount.getBalance() + money);
			tmemberassetaccount.setAfreason(null);
			tmemberassetaccountDao.save(tmemberassetaccount);
		}
	}

	// 还款
	@Override
	public Tfinanceinfo pay(Tfinanceinfo tfinanceinfo, Tuser tuser) {
		// 判断不能提早还款
//		if (new Date().getTime() < tfinanceinfo.getNrdate().getTime()) {
//			return null;
//		}
		// 判断用户余额是否足够
		Tmember tmember = tfinanceinfo.getTmember();
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("Tmember", tmember);
		Tmemberassetaccount tmemberassetaccount = tmemberassetaccountDao.getTmemberassetaccount(queryMap).get(0);
		if (tfinanceinfo.getSubpri() + tfinanceinfo.getAlino() + tfinanceinfo.getMftba() > tmemberassetaccount.getBalance()) {
			return null;
		}
		double payMoney = tfinanceinfo.getSubpri() + tfinanceinfo.getAlino() + tfinanceinfo.getMftba();
		double returnMoney = tfinanceinfo.getSubpri() + tfinanceinfo.getAlino();
		// 标的发出者余额变动
		tmemberassetaccount.setBalance(tmemberassetaccount.getBalance() - payMoney);
		Tmemberassetaccountdetails tcd = new Tmemberassetaccountdetails(tmember, tfinanceinfo.getSubpri() + tfinanceinfo.getAlino(),
				Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_OUT, Tmemberassetaccountdetails.TRANTYPE_PAYMONEY, new Date(), tfinanceinfo.getFiid().toString(), null);
		tmemberassetaccountdetailsDao.save(tcd);
		tcd = new Tmemberassetaccountdetails(tmember, tfinanceinfo.getMftba(), Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_OUT, Tmemberassetaccountdetails.MANAGEMENTFEE,
				new Date(), "平台", null);
		tmemberassetaccountdetailsDao.save(tcd);
		// 投资者余额变动
		Set<Ttenderrecord> tenderSet = tfinanceinfo.getTtenderrecords();
		for (Ttenderrecord t : tenderSet) {
			Tmember tm = t.getTmember();
			Map<String, Object> tempMap = new HashMap<String, Object>();
			tempMap.put("Tmember", tm);
			Tmemberassetaccount tmpaccount = tmemberassetaccountDao.getTmemberassetaccount(tempMap).get(0);
			//计算投资者的投资比例
//			double p = t.getTdmoney() / tfinanceinfo.getFinanceamount();
			double BJ = 0.0;
			double LX = 0.0;
			if (tfinanceinfo.getRepaymentmod() == 1 || tfinanceinfo.getRepaymentmod() == 2) {
				BJ = getMoney(t,benjin);
				LX = getMoney(t, lixi);
			}
			if (tfinanceinfo.getRepaymentmod() == 3)
				LX = getMoney(t, benxi);
			tmpaccount.setBalance(tmpaccount.getBalance() + BJ +LX);
			//交易明细 利息收入
			Tmemberassetaccountdetails ttbc = new Tmemberassetaccountdetails(tm,LX, Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_IN, Tmemberassetaccountdetails.TRANTYPE_INST,
					new Date(), tfinanceinfo.getFiid().toString(), null);
			tmemberassetaccountdetailsDao.save(ttbc);
			//交易明细本金收入
//			if(tfinanceinfo.get)
			if (tfinanceinfo.getRepaymentmod() == 1 || tfinanceinfo.getRepaymentmod() == 2) {
				ttbc = new Tmemberassetaccountdetails(tm, BJ, Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_IN, Tmemberassetaccountdetails.TRANTYPE_MIMONEY, new Date(), tfinanceinfo
						.getFiid().toString(), null);
				tmemberassetaccountdetailsDao.save(ttbc);
				// 减去计息金额
				t.setMibmoney(t.getMibmoney() - BJ);
			}
			ttenderrecordService.save(t);
			//还款的时候发送邮件给每一位投资者
			ttenderrecordService.sendRefundMail(t.getTrid());
		}
		// 标的下一还款日和各待还金额变更
		List<Map<String, Double>> payList = ErFen.principal(tfinanceinfo.getFinanceamount(), tfinanceinfo.getFinancepa() / 12, tfinanceinfo.getFinanceallotedtime() / 30);
		int datesub = DateUtil.getMonthSpace(tfinanceinfo.getNrdate(), tfinanceinfo.getItfdate());
		// Map<String, Object> map2 = new HashMap<String, Object>();
		// map2.put("otherside", tfinanceinfo.getFiid());
		// map2.put("borrowing", -1);
		// map2.put("trantype",
		// Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_OUT);
		// List<Tmemberassetaccountdetails> detail =
		// tmemberassetaccountdetailsDao.getTmemberassetaccountdetails(map2);
		if (datesub >= (tfinanceinfo.getFinanceallotedtime() / 30)) {
			tfinanceinfo.setSubpri(null);
			tfinanceinfo.setAlino(null);
			tfinanceinfo.setMftba(null);
			tfinanceinfo.setNrdate(null);
			tfinanceinfo.setStatus(TFINANCEINFO_STATUS_CLEAR);
		} else if(tfinanceinfo.getRepaymentmod()==1||tfinanceinfo.getRepaymentmod()==2){
			//等额本息
			Map<String, Double> payMap = payList.get(datesub);
			tfinanceinfo.setSubpri(payMap.get(benjin));
			tfinanceinfo.setAlino(payMap.get(lixi));
			tfinanceinfo.setNrdate(DateUtil.addMonth(tfinanceinfo.getNrdate(), 1));
		}else if(tfinanceinfo.getRepaymentmod()==3){
			//每月还息到期还本
			if ((tfinanceinfo.getFinanceallotedtime() / 30) - datesub > 1) {//判断还款是否最后一期, 如果是最后一期即将本金加入下一还款金额中
				tfinanceinfo.setSubpri(0.0);
				tfinanceinfo.setAlino(ErFen.culMonthlyInterest(tfinanceinfo.getFinanceamount(), tfinanceinfo.getFinancepa()));
				tfinanceinfo.setNrdate(DateUtil.addMonth(tfinanceinfo.getNrdate(), 1));
			} else {
				tfinanceinfo.setSubpri(tfinanceinfo.getFinanceamount());
				tfinanceinfo.setAlino(ErFen.culMonthlyInterest(tfinanceinfo.getFinanceamount(), tfinanceinfo.getFinancepa()));
				tfinanceinfo.setNrdate(DateUtil.addMonth(tfinanceinfo.getNrdate(), 1));
			}
		}
		return tfinanceinfoDao.save(tfinanceinfo);
	}
	
	//计算本金(principalMonth),利息(interestMonth)
	private double getMoney(Ttenderrecord ttenderrecord,String key){
		Tfinanceinfo tfinanceinfo = ttenderrecord.getTfinanceinfo();
		List<Map<String, Double>> payList = null;
		if(1==tfinanceinfo.getRepaymentmod()){
			payList = ErFen.principal(ttenderrecord.getTdmoney(), tfinanceinfo.getFinancepa() / 12, tfinanceinfo.getFinanceallotedtime() / 30);
		}
		if(3==tfinanceinfo.getRepaymentmod()){
			payList = ErFen.monthly(ttenderrecord.getTdmoney(), tfinanceinfo.getFinancepa() / 12, tfinanceinfo.getFinanceallotedtime() / 30);
		}
		int datesub = DateUtil.getMonthSpace(tfinanceinfo.getNrdate(), tfinanceinfo.getItfdate());
		Map<String, Double> payMap = payList.get(datesub-1);
		return payMap.get(key);
	}
	

	@Override
	public FinanceHelper getFinanceHelper(Tmember tmember) {
		FinanceHelper helper = new FinanceHelper();
		helper.setTmember(tmember);
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("Tmember", tmember);
		List<Tfinanceinfo> list = tfinanceinfoDao.getTfinanceinfo(queryMap);
		helper.setBorrowNum(list.size());
		for (Tfinanceinfo t : list) {
			int status = t.getStatus();
			helper.setBorrowMoney(helper.getBorrowMoney() + t.getFinanceamount());
			if (TFINANCEINFO_STATUS_FAIL == status || TFINANCEINFO_STATUS_LOAN_FAIL == status) {
				helper.setBorrowFail((helper.getBorrowFail()) + 1);
			}
			if (TFINANCEINFO_STATUS_CLEAR == status) {
				helper.setBorrowClear(helper.getBorrowClear() + 1);
			}
			if (TFINANCEINFO_STATUS_LOAN_SUCCESS == status) {
				helper.setNextPay(helper.getNextPay() + t.getSubpri() + t.getAlino() + t.getMftba());
				helper.setPayying(helper.getPayying() + 1);
			}
			if (status>=6&&status!=10) {
				helper.setBorrowSuccess(helper.getBorrowSuccess() + 1);
			}
			if (9 == status || 11 == status) {
				helper.setBorrowDelay(helper.getBorrowDelay() + 1);
			}

		}
		return helper;
	}

	public List<Tfinanceinfo> getYED() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("targettype", this.TFINANCEINFO_TARGETTYPE_YED);
		map.put("status", 2);
		return tfinanceinfoDao.getTfinanceinfo(map);
	}

	// 余额贷每日计算利息功能
	@Override
	public String YEDPay(Tfinanceinfo tfinanceinfo) {
		//加入日期控制, 避免重复还息
//		if(null!=tfinanceinfo.getNrdate()){
//			if(new Date().getTime()/60000 < tfinanceinfo.getNrdate().getTime()/60000){
//				return null;
//			}
//		}
		Set<Ttenderrecord> set = tfinanceinfo.getTtenderrecords();
//		double totalmoney = 0;
		double paymoney = 0;
		Tmember tmember = null;
		Tmemberassetaccount acount = null;
		Tmemberassetaccount acount2 = null;
		Tmemberassetaccountdetails detail = null;
		Map<String, Object> map = new HashMap<String, Object>();
		for (Ttenderrecord t : set) {
			// 余额贷
			if (DateUtil.getDaySpace(t.getTddatetime(), new Date()) < 1)
				continue;
			// 计算还息金额
			paymoney = ErFen.disposable(t.getMibmoney(), t.getFinancepa(), 1);
			// 判断如果还息金额为0则不记录交易明细
			if (paymoney <= 0)
				continue;
			// 投资人
			tmember = t.getTmember();
			map.put("Tmember", tmember);
			acount = tmemberassetaccountDao.getTmemberassetaccount(map).get(0);
			acount.setBalance(acount.getBalance() + paymoney);
			tmemberassetaccountDao.save(acount);
			detail = new Tmemberassetaccountdetails(tmember, paymoney, Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_IN, Tmemberassetaccountdetails.YED_INST_IN, new Date(),
					tfinanceinfo.getFiid().toString(), null);
			tmemberassetaccountdetailsDao.save(detail);
			// totalmoney += paymoney;
			// 融资人还款
			Tmember tmember2 = tfinanceinfo.getTmember();
			map.put("Tmember", tmember2);
			acount2 = tmemberassetaccountDao.getTmemberassetaccount(map).get(0);
			acount2.setBalance(acount2.getBalance() - paymoney);
			detail = new Tmemberassetaccountdetails(tmember2, paymoney, Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_OUT, Tmemberassetaccountdetails.YED_INST_OUT, new Date(),
					tfinanceinfo.getFiid().toString(), null);
			tmemberassetaccountDao.save(acount2);
			tmemberassetaccountdetailsDao.save(detail);
		}
		if (null != tfinanceinfo.getNrdate()) {
			tfinanceinfo.setNrdate(DateUtil.addDate(tfinanceinfo.getNrdate(), 1));
			tfinanceinfoDao.save(tfinanceinfo);
		}
		return null;
	}
	//发送邮件给融资者
	@Override
	public void sendFullMail(long fiid) {
		// 设置两位小数点
		DecimalFormat df = new DecimalFormat("0.00");
		// 设置返回日期的格式
		SimpleDateFormat dateformatAll = new SimpleDateFormat("yyyy年MM月dd日");
		// 获取当前标的ID
		Tfinanceinfo tfinanceinfo = this.get(fiid);
		// 获取memberid
		Tmember tmember = tfinanceinfo.getTmember();
		// 设置其他表的memberid字段
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Tmember", tmember);
		// 获取对应mamberid的会员信用
		Tmembercredit tmembercredit = tmembercreditService.getTmembercredit(map).get(0);
		// 设置提现银行
		map.put("iswithdraw", 1);
		// 获取银行名称
		String bank = null;
		// 获取银行卡号
		String bankcard = "";
		// 获取对应mamberid的会员银行卡
		Tmemberbankcard tmemberbankcard;
		if (1 == tmemberbankcardService.getTmemberbankcard(map).size()) {
			tmemberbankcard = tmemberbankcardService.getTmemberbankcard(map).get(0);
			bank = "银行名称：" + tmemberbankcard.getBank();
			bankcard = "，银行卡号：" + tmemberbankcard.getBankcard();
		} else {
			bank = "你还没有设置银行卡，请添加银行卡！";
		}
		Map<String, Object> map2 = new HashMap<String, Object>();
		// 设置信用对应的费率
		map2.put("feedcode", Tmemberrates.PRE_RATE_SERVICE + tmembercredit.getCreditrating());
		// 获取费率
		Tmemberrates tmemberrates = tmemberratesService.getTmemberrates(map2).get(0);
		// 获取充值手续费
		Tmemberrates tmemberrates1 = tmemberratesService.getFee(Tmemberrates.RECHARGE_FEE);
		// 要发送的邮箱
		String email = tmember.getEmail();
		// 下一还款金额
		double next = tfinanceinfo.getSubpri() + tfinanceinfo.getAlino() + tfinanceinfo.getMftba();
		// 会员要充值多少钱
		double chong = next + next * tmemberrates1.getRates() * (1 + tmemberrates1.getRates());
		// 发送日期
		java.util.Calendar c = java.util.Calendar.getInstance();
		java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyyy年MM月dd日");
		//发送主题
		String subject = "放款邮件通知";
		
		StringBuffer s = new StringBuffer();
		s.append(tmember.getTruename());
		s.append(",你好!\n        你申请的融资标的（融资标的ID是:");
		s.append(tfinanceinfo.getFiid());
		s.append(" 融资关键字是：");
		s.append(tfinanceinfo.getFinancekey());
		s.append("，融资金额");
		s.append(df.format(tfinanceinfo.getFinanceamount()));
		s.append("元，融资期限");
		s.append(tfinanceinfo.getFinanceallotedtime()/30);
		s.append("个月，年利率");
		s.append(df.format(tfinanceinfo.getFinancepa()*100));
		s.append("%）已满标，贷一贷平台已放款到你提现账户上（");
		s.append(bank);
		s.append(bankcard);
		s.append("），放款金额是");
		s.append(df.format(tfinanceinfo.getFinanceamount()-tfinanceinfo.getFinanceamount()*tmemberrates.getRates()));
		s.append("元。该融资标的还款方式: ");
		s.append(DictUtils.getDictByType(DictUtils.TFINANCEINFO_REPAYMENTMOD).get(tfinanceinfo.getRepaymentmod().toString()));
		s.append("，下一还款日期：");
		s.append(dateformatAll.format(tfinanceinfo.getNrdate()));
		s.append("，下一还款金额：");
		s.append(df.format(next));
		s.append("元（其中待还本金：");
		s.append(df.format(tfinanceinfo.getSubpri()));
		s.append("元， 待还利息：");
		s.append(df.format(tfinanceinfo.getAlino()));
		s.append("元， 待还管理费：");
		s.append(df.format(tfinanceinfo.getMftba()));
		s.append("元（借款管理费费率：");
		s.append(df.format(tfinanceinfo.getMfrl()*100));
		s.append("%，按期收取，");
		s.append(df.format(tfinanceinfo.getMftba()));
		s.append("=");
		s.append(df.format(tfinanceinfo.getFinanceamount()));
		s.append("*");
		s.append(df.format(tfinanceinfo.getMfrl() * 100));
		s.append("%）），请按时足额还款，维持良好信用。\n        还款提示：上贷一贷www.51d1d.com，登录你的账户，“资金管理”-“充值”，进入充值界面，选择银行、填写充值金额，充值时第三方支付平台要收取充值金额的");
		s.append(df.format(tmemberrates1.getRates() * 100));
		s.append("%作为充值手续费，你下次还款时建议你充值");
		s.append(df.format(chong));
		s.append("，即");
		s.append(df.format(chong));
		s.append("= ");
		s.append(df.format(next));
		s.append('+');
		s.append(df.format(next));
		s.append('*');
		s.append(df.format(tmemberrates1.getRates() * 100));
		s.append("%*（1+");
		s.append(tmemberrates1.getRates());
		s.append("）。\n        如有疑问，请及时联系我们，联系方式如下：\n        1、400电话：400-1122-363\n        2、平台固话：020-85698359\n        最后，祝你生意兴隆，财源广进！\n                                  贷一贷\n                            ");
		s.append(f.format(c.getTime()));
		
		String content = s.toString();
		// 发送邮件
		
		try {
			EmailTools.sendEmail(content, subject, email);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	//筛选可投标的列表
	@Override
	public Pagination getEnableFinanceByCondition(String[] targetType, List<Map<String, Integer>> dateList, String[] credit,int pageNo, int pageSize) {
		return tfinanceinfoDao.getFinanceInfoByCondition(targetType, dateList, credit,pageNo, pageSize);
	}
}